import React from 'react';
import { Select, Input, Radio, InputNumber, Checkbox, DatePicker, Button, TimePicker } from 'antd';
import TurnoverProcess from '@/pages/WorkFlow/components/CustomComponents/TurnoverProcess';
import TurnoverByLeader from '@/pages/WorkFlow/components/CustomComponents/TurnoverByLeader';
import Vacation from '@/pages/WorkFlow/components/CustomComponents/Vacation';
import GoOut from '@/pages/WorkFlow/components/CustomComponents/GoOut';
import LackCard from '@/pages/WorkFlow/components/CustomComponents/LackCard';
import Overtime from '@/pages/WorkFlow/components/CustomComponents/Overtime';
import PostApply from '@/pages/WorkFlow/components/CustomComponents/PostApply';
import VacationCancel from '@/pages/WorkFlow/components/CustomComponents/VacationCancel';
import BusinessTrip from '@/pages/WorkFlow/components/CustomComponents/BusinessTrip';
import Handover from '@/pages/WorkFlow/components/CustomComponents/Handover';
import Institution from '@/pages/WorkFlow/components/CustomComponents/Institution';
import PostChange from '@/pages/WorkFlow/components/CustomComponents/PostChange';
import AuthManage from '@/pages/WorkFlow/components/CustomComponents/FunctionManagement';
import Organization from '@/pages/WorkFlow/components/CustomComponents/Organization';
import Recruit from '@/pages/WorkFlow/components/CustomComponents/Recruitment';
import PostRank from '@/pages/WorkFlow/components/CustomComponents/PostRank';
import SalaryApply from '@/pages/WorkFlow/components/CustomComponents/SalaryApply';
import NewsApply from '@/pages/WorkFlow/components/CustomComponents/NewsApply';
import Hire from '@/pages/WorkFlow/components/CustomComponents/Hire';
import DimissionApply from '@/pages/WorkFlow/components/CustomComponents/DimissionApply';
import DimissionProxyApply from '@/pages/WorkFlow/components/CustomComponents/DimissionProxyApply';
import Regular from '@/pages/WorkFlow/components/CustomComponents/Regular';
import NewFunction from '@/pages/WorkFlow/components/CustomComponents/NewFunction';
// import FunctionManagement from '@/pages/WorkFlow/components/CustomComponents/FunctionManagement';
import PrivilegeTemplate from '@/pages/WorkFlow/components/CustomComponents/PrivilegeTemplate';
import VocationWithdrawal from '@/pages/WorkFlow/components/CustomComponents/VocationWithdrawal';
import SupervisorSet from '@/pages/WorkFlow/components/CustomComponents/SupervisorSet';
import SalaryTemplateApply from '@/pages/WorkFlow/components/CustomComponents/SalaryTemplateApply';
import SalarySetGrantApply from '@/pages/WorkFlow/components/CustomComponents/SalarySetGrantApply';
import SalaryReCheckApply from '@/pages/WorkFlow/components/CustomComponents/SalaryReCheckApply';
import SalarySetCpfApply from '@/pages/WorkFlow/components/CustomComponents/SalarySetCpfApply';
import SalaryProcessApply from '@/pages/WorkFlow/components/CustomComponents/SalaryProcessApply';
import SalarySetShgApply from '@/pages/WorkFlow/components/CustomComponents/SalarySetShgApply';
import TransferPositionApply from '@/pages/WorkFlow/components/CustomComponents/TransferPositionApply';
import SalarySetSdlApply from '@/pages/WorkFlow/components/CustomComponents/SalarySetSdlApply';

import Icon from '@/pages/WorkFlow/components/Upload/Icon';
import moment from 'moment';
import TagList from '@/components/Custom/TagList';
// import Area from './components/Area';
import CityPicker from '@/components/CityPicker';
import RichText from '@/components/RichText';
import MedicalSocialSecurityApply from '@/pages/WorkFlow/components/CustomComponents/MedicalSocialSecurityApply';
import PersonalIncomeApply from '@/pages/WorkFlow/components/CustomComponents/PersonalIncomeApply';
import OrganizationTree from './components/OrganizationTree';
import FunctionalTree from './components/FunctionalTree';
import ContactsInput from './components/ContactsInput';

import OssUpload from '../OssUpload';
import Amount from './components/Amount';
import LeaveType from './components/LeaveType';
import LeaveDatePicker from './components/LeaveDatePicker';
import Leave from './components/Leave';
import Duration from './components/Duration';
import LeaveReason from './components/LeaveReason';
import ReleaseType from './components/ReleaseType';
import EffectiveDate from './components/EffectiveDate';
import InstitutionType from './components/InstitutionType';
import EditableTagGroup from './components/EditableTagGroup';
import CompanyTree from './components/CompanyTree';
import NewsTypesSelect from './components/NewsTypesSelect';
import ContentEditor from './components/ContentEditor';

const { MonthPicker, RangePicker } = DatePicker;
const { Option } = Select;

const COMMON_STYLE = {
    width: '100%'
};

class FormCheckbox extends React.PureComponent {
    handleChange = () => {
        this.props.onChange(!this.props.value);
    };

    render() {
        return (
            <div>
                <Checkbox checked={this.props.value} onChange={this.handleChange}>
                    {this.props.options && this.props.options.label}
                </Checkbox>
            </div>
        );
    }
}

/*
    自定义或第三方的表单控件需符合和form自定义表单控件
    提供受控属性 value 或其它与 valuePropName 的值同名的属性。
    提供 onChange 事件或 trigger 的值同名的事件。
    支持 ref：
    React@16.3.0 之前只有 Class 组件支持。
    React@16.3.0 及之后可以通过 forwardRef 添加 ref 支持
*/

/**
 * @param config<object> 标签名称
 * @param form form对象
 * @param onChange<fn> 自定义表单所需的onChange事件
 * @param value<any> 自定义表单所需的value
 * @param otherProps<object> 组件额外所需参数
 * */

const fNOP = () => {};
const AutoRenderComponent = (
    { config, form, onChange, value, employeeCode, organizationCode, setSubmitLoading = fNOP, ...otherProps },
    ref
) => {
    // 日期format类型
    const rangePickerFormatType = {
        yearPricker: {
            format: ['YYYY-MM-DD', 'YYYY-MM-DD'],
            showTime: false
        },
        hourPricker: {
            format: ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'],
            showTime: true
        },
        hourMinutePricker: {
            format: ['YYYY-MM-DD HH:mm', 'YYYY-MM-DD HH:mm'],
            showTime: { format: 'HH:mm' }
        }
    };
    const renderFormItem = item => {
        const { tag, dataList, options } = item;
        // 组件props
        const tagCommonProps = {
            style: COMMON_STYLE,
            onChange,
            value,
            setSubmitLoading,
            ...options,
            ...otherProps,
            ref
        };
        // 时间格式化
        const dateFormatProps = { ...tagCommonProps, value: value ? moment(tagCommonProps.value) : undefined };
        const rangeDateFormatProps = {
            ...tagCommonProps,
            value: Array.isArray(value) ? value.map(it => moment(it)) : []
        };

        switch (tag) {
            case 'Input': // 输入框
                return <Input {...tagCommonProps} />;
            case 'TextArea': // 多行文本
                return <Input.TextArea rows={4} {...tagCommonProps} />;
            case 'InputNumber': // 数字输入框
                return <InputNumber {...tagCommonProps} maxLength={15} />;
            case 'Select': // 选择器
            case 'MultipleSelect':
                return (
                    <Select {...tagCommonProps} getPopupContainer={trigger => trigger.parentNode}>
                        {(dataList || []).map((o, index) => (
                            <Option key={index.toString()} value={o.value ?? o.key} title={o.label}>
                                {o.label}
                            </Option>
                        ))}
                    </Select>
                );
            case 'RadioGroup': // 单选组合
                return (
                    <Radio.Group {...tagCommonProps}>
                        {item.dataList &&
                            item.dataList.map((o, index) => (
                                <Radio value={o.value} key={index.toString()}>
                                    {o.label}
                                </Radio>
                            ))}
                    </Radio.Group>
                );
            case 'Date': // 日期
                if (item.dataType === 'yearTime') {
                    return (
                        <DatePicker
                            format="YYYY-MM-DD HH:mm:ss"
                            {...dateFormatProps}
                            getCalendarContainer={trigger => trigger.parentNode}
                            showTime
                            ref={ref}
                        />
                    );
                }
                if (item.dataType === 'month') {
                    return (
                        <MonthPicker
                            format="YYYY-MM"
                            {...dateFormatProps}
                            getCalendarContainer={trigger => trigger.parentNode}
                            ref={ref}
                        />
                    );
                }
                if (item.dataType === 'hourMinute') {
                    return (
                        <DatePicker
                            format="YYYY-MM-DD HH:mm"
                            {...dateFormatProps}
                            showTime={{ format: 'HH:mm' }}
                            getCalendarContainer={trigger => trigger.parentNode}
                            ref={ref}
                        />
                    );
                }
                return (
                    <DatePicker
                        format="YYYY-MM-DD"
                        {...dateFormatProps}
                        getCalendarContainer={trigger => trigger.parentNode}
                        ref={ref}
                    />
                );
            case 'CheckboxGroup': // 多选框组合
                return (
                    <Checkbox.Group {...tagCommonProps}>
                        {item.dataList
                            .map((it, index) => ({ key: index, ...it }))
                            .map(o => (
                                <Checkbox value={o.value} key={o.key}>
                                    {o.label}
                                </Checkbox>
                            ))}
                    </Checkbox.Group>
                );
            case 'Amount': // 金额
                return <Amount {...tagCommonProps} />;
            case 'CheckBox': // 多选框
                return <FormCheckbox options={options} ref={ref} />;
            case 'Title': // 标题
                return (
                    <div {...tagCommonProps} style={{ fontSize: 16, fontWeight: 'bold' }}>
                        {item.titleValue}
                        {item.tips && (
                            <small style={{ fontSize: 12, fontWeight: 'normal', color: '#999' }}>
                                {item.subTitleValue}
                            </small>
                        )}
                    </div>
                );
            case 'OssUpload':
                return (
                    <OssUpload {...tagCommonProps} {...item.uploadProps}>
                        <Button {...options}>
                            <Icon type="upload" /> {item.buttonText}
                        </Button>
                    </OssUpload>
                );
            case 'ImageOssUpload':
                return <OssUpload {...tagCommonProps} {...item.uploadProps} />;
            case 'RangePicker':
                return (
                    <RangePicker
                        format={(item.pickerType && rangePickerFormatType[item.pickerType].format) || 'YYYY-MM-DD'}
                        showTime={(item.pickerType && rangePickerFormatType[item.pickerType].showTime) || false}
                        getCalendarContainer={trigger => trigger.parentNode}
                        {...rangeDateFormatProps}
                        ref={ref}
                    />
                );
            case 'ContactsInput':
                // 联系人
                return <ContactsInput {...tagCommonProps} />;
            case 'Link':
                return (
                    <a href={item.linkUrl} {...tagCommonProps} target="_blank" rel="noopener noreferrer">
                        {item.linkText}
                    </a>
                );
            case 'TimePicker':
                return (
                    <TimePicker
                        format="HH:mm:ss"
                        {...dateFormatProps}
                        getPopupContainer={trigger => trigger.parentNode}
                        ref={ref}
                    />
                );
            case 'Vacation': // 剩余假期结算方式
                return (
                    <Vacation
                        dataSource={item}
                        form={form}
                        employeeCode={employeeCode}
                        organizationCode={organizationCode}
                        {...tagCommonProps}
                    />
                );
            case 'CompanyTree':
                return <CompanyTree {...tagCommonProps} />;
            case 'ReleaseType':
                return <ReleaseType {...tagCommonProps} />;
            case 'EditableTagGroup':
                return <EditableTagGroup {...tagCommonProps} />;
            case 'EffectiveDate':
                return <EffectiveDate {...tagCommonProps} />;
            case 'InstitutionType':
                return <InstitutionType {...tagCommonProps} />;
            case 'Turnover': // 员工发起离职
                return <TurnoverProcess dataSource={item} form={form} {...tagCommonProps} />;
            case 'TurnoverByLeader': // 代发起离职
                return <TurnoverByLeader dataSource={item} form={form} {...tagCommonProps} />;
            case 'Area': // 省市地区
                return <CityPicker {...tagCommonProps} />;
            case 'OrganizationTree': // 行政机构
                return <OrganizationTree {...tagCommonProps} />;
            case 'FunctionalTree': // 组织机构/职能机构
                return <FunctionalTree {...tagCommonProps} />;
            case 'Leave': // 请假
                return <Leave dataSource={item} form={form} {...tagCommonProps} />;
            case 'LeaveType': // 请假
                return <LeaveType {...tagCommonProps} />;
            case 'LeaveDatePicker': //
                return <LeaveDatePicker {...tagCommonProps} />;
            case 'NewsTypesSelect': // 新闻类型
                return <NewsTypesSelect {...tagCommonProps} />;
            case 'ContentEditor': // 富文本
                return <ContentEditor {...tagCommonProps} />;
            case 'RichText': // 富文本公有
                return <RichText {...tagCommonProps} />;
            case 'TagList': // 标签编辑器
                return <TagList {...tagCommonProps} />;
            case 'GoOut': // 外出
                return <GoOut dataSource={item} form={form} {...tagCommonProps} />;
            case 'Duration': // 时长
                return <Duration {...tagCommonProps} />;
            case 'Overtime': // 加班
                return <Overtime dataSource={item} form={form} {...tagCommonProps} />;
            case 'LackCard': // 外出
                return <LackCard dataSource={item} form={form} {...tagCommonProps} />;
            case 'PostApply': // 岗位申请
                return <PostApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'LeaveCancel': // 销假
                return <VacationCancel dataSource={item} form={form} {...tagCommonProps} />;
            case 'BusinessTrip':
                return <BusinessTrip dataSource={item} form={form} {...tagCommonProps} />;
            case 'Handover':
                return <Handover dataSource={item} form={form} {...tagCommonProps} />;
            case 'LeaveReason':
                return <LeaveReason form={form} {...tagCommonProps} />;
            case 'Institution': // 制度申请
                return <Institution dataSource={item} form={form} {...tagCommonProps} />;
            case 'PostChange': // 制度申请
                return <PostChange dataSource={item} form={form} {...tagCommonProps} />;
            case 'AuthManage':
                return <AuthManage dataSource={item} form={form} {...tagCommonProps} />;
            case 'Organization': // 机构变更
                return <Organization dataSource={item} form={form} {...tagCommonProps} />;
            case 'Recruit': // 机构变更
                return <Recruit dataSource={item} form={form} {...tagCommonProps} />;
            case 'OrgRankApply': // 职级
                return <PostRank dataSource={item} form={form} {...tagCommonProps} />;
            case 'OrgRankTypeApply': // 职级类型
                return <PostRank dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalaryApply': // 薪资参考
                return <SalaryApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'NewsApply': // 薪资参考
                return <NewsApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'RecruitEmployApply': // 录用类型
                return <Hire dataSource={item} form={form} {...tagCommonProps} />;
            case 'DimissionApply': // 离职审批
                return <DimissionApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'DimissionProxyApply': // 离职代审批
                return <DimissionProxyApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'RegularApply': // 转正申请类型
                return <Regular dataSource={item} form={form} {...tagCommonProps} />;
            case 'NewFunctionApply': // 新功能
                return <NewFunction dataSource={item} form={form} {...tagCommonProps} />;
            // case 'FunctionManagement': // 权限管理-新功能申请套件
            //     return <FunctionManagement dataSource={item} form={form} {...tagCommonProps} />;
            case 'PrivilegeTemplateApply': // 权限管理-权限模板申请
                return <PrivilegeTemplate dataSource={item} form={form} {...tagCommonProps} />;
            case 'VocationWithdrawal': // 假期余额转折薪酬套件
                return <VocationWithdrawal dataSource={item} form={form} {...tagCommonProps} />;
            case 'LeaderSettingApply': // 主管设置申请套件
                return <SupervisorSet dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalaryTemplateApply': // 月模板配置修改记录
                return <SalaryTemplateApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalarySetGrantApply': // 发放流程
                return <SalarySetGrantApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalarySetSocialApply': // 险金流程
                return <MedicalSocialSecurityApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalarySetTaxApply': // 个税预扣率变更
                return <PersonalIncomeApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalaryReCheckApply': // 薪资审批
                return <SalaryReCheckApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalarySetCpfApply': // 公积金变更
                return <SalarySetCpfApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalaryProcessApply': // 特殊人员-薪资审批
                return <SalaryProcessApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalarySetShgApply': // 险金档案 SHG 审批
                return <SalarySetShgApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'TransferPositionApply': // 调岗
                return <TransferPositionApply dataSource={item} form={form} {...tagCommonProps} />;
            case 'SalarySetSdlApply':// 技能发展税 审批
                return <SalarySetSdlApply dataSource={item} form={form} {...tagCommonProps}/>
            default:
                return null;
        }
    };

    return renderFormItem(config);
};

export default React.forwardRef(AutoRenderComponent);
